const homeMethods = {

}

// 获取时间
homeMethods.timeToSeconds = (timeString = '') => {
    if(timeString.includes(':')) {
        const [hours, minutes] = timeString.split(':').map(Number);
        return (hours * 3600) + (minutes * 60);
    }else {
        return 0
    }
}


// 获取工作了多少秒
homeMethods.calculateWorkedSeconds = (workingHours) => {
    const now = new Date();
    const currentHours = now.getHours();
    const currentMinutes = now.getMinutes();
    const currentSeconds = now.getSeconds();
    const currentTotalSeconds = (currentHours * 3600) + (currentMinutes * 60) + currentSeconds;

    let totalWorkedSeconds = 0;

    workingHours.forEach(period => {
        const [startHours, startMinutes] = period.startTime.split(':').map(Number);
        const [endHours, endMinutes] = period.endTime.split(':').map(Number);

        const startTotalSeconds = (startHours * 3600) + (startMinutes * 60);
        const endTotalSeconds = (endHours * 3600) + (endMinutes * 60);

        // 如果当前时间在该时间段内
        if (currentTotalSeconds >= startTotalSeconds && currentTotalSeconds <= endTotalSeconds) {
            totalWorkedSeconds += currentTotalSeconds - startTotalSeconds;
        }
        // 如果当前时间已过该时间段
        else if (currentTotalSeconds > endTotalSeconds) {
            totalWorkedSeconds += endTotalSeconds - startTotalSeconds;
        }
        // 当前时间未到该时间段则不计入
    });

    return totalWorkedSeconds;
}

// 获取本月工作日
homeMethods.getWorkingDayCount = () => {
    const now = new Date();
    const year = now.getFullYear();
    const month = now.getMonth() + 1; // getMonth() 返回 0-11，需 +1

    let count = 0;
    const daysInMonth = new Date(year, month, 0).getDate();

    for (let day = 1; day <= daysInMonth; day++) {
        const dayOfWeek = new Date(year, month - 1, day).getDay();
        if (dayOfWeek >= 1 && dayOfWeek <= 5) { // 周一至周五
            count++;
        }
    }

    return count;
}

homeMethods.roundToDecimals = (amount, decimals = 2) => {
    return Number(Number(amount).toFixed(2)); // 恢复符号并返回
}

/**
 * 获取当月1日到今天的工作日数量，支持自定义周六和周日是否为工作日
 * @param {Array<string|Date>} excludeDates - 要排除的日期列表，可以是日期字符串或Date对象
 * @param {Object} [workdayConfig] - 可选参数，工作日配置对象
 * @param {boolean} [workdayConfig.saturday=false] - 周六是否视为工作日，默认值为false
 * @param {boolean} [workdayConfig.sunday=false] - 周日是否视为工作日，默认值为false
 * @returns {number} 工作日数量
 */
homeMethods.getWorkingDaysUntilToday = (excludeDates = [], workdayConfig = {
    saturday: false,
    sunday: false
}) => {
    const { saturday = false, sunday = false } = workdayConfig;
    const today = new Date();
    const year = today.getFullYear();
    const month = today.getMonth(); // 0-11 表示 1-12 月

    let workingDayCount = 0;
    const daysInMonth = new Date(year, month + 1, 0).getDate(); // 当月总天数

    // 将排除日期转换为 Date 对象数组并预处理
    const excludeDateObjects = excludeDates
        .map(date => new Date(date))
        .map(date => {
            date.setHours(0, 0, 0, 0);
            return date;
        });

    // 遍历当月的每一天
    for (let day = 1; day <= daysInMonth; day++) {
        const currentDate = new Date(year, month, day);
        const dayOfWeek = currentDate.getDay(); // 0（周日）到 6（周六）

        // 判断当前日期是否为排除日期
        const isExcluded = excludeDateObjects.some(excludeDate =>
            excludeDate.getTime() === currentDate.getTime()
        );

        // 判断当前日期是否为工作日
        const isWeekday =
            (dayOfWeek >= 1 && dayOfWeek <= 5) ||  // 周一至周五
            (dayOfWeek === 6 && saturday) ||       // 周六（如果配置为工作日）
            (dayOfWeek === 0 && sunday);          // 周日（如果配置为工作日）

        // 如果是工作日且不在排除列表中
        if (isWeekday && !isExcluded) {
            workingDayCount++;
        }
    }

    return workingDayCount;
}

/**
 * 获取当月1日到今天的工作日数量，支持自定义周六和周日是否为工作日
 * @param {Array<string|Date>} excludeDates - 要排除的日期列表，可以是日期字符串或Date对象
 * @param {Object} [workdayConfig] - 可选参数，工作日配置对象
 * @param {boolean} [workdayConfig.saturday=false] - 周六是否视为工作日，默认值为false
 * @param {boolean} [workdayConfig.sunday=false] - 周日是否视为工作日，默认值为false
 * @returns {number} 工作日数量
 */
homeMethods.getWorkDaysUntilToday = (excludeDates = [], workdayConfig = {
    saturday: false,
    sunday: false
}) => {
    const { saturday = false, sunday = false } = workdayConfig;
    const today = new Date();
    const year = today.getFullYear();
    const month = today.getMonth(); // 0-11 表示 1-12 月
    const todayDate = today.getDate(); // 今天是当月的第几天

    let workingDayCount = 0;

    // 将排除日期转换为 Date 对象数组并预处理
    const excludeDateObjects = excludeDates
        .map(date => new Date(date))
        .map(date => {
            date.setHours(0, 0, 0, 0);
            return date;
        });

    // 遍历当月1日到今天的每一天
    for (let day = 1; day <= todayDate; day++) {
        const currentDate = new Date(year, month, day);
        const dayOfWeek = currentDate.getDay(); // 0（周日）到 6（周六）

        // 判断当前日期是否为排除日期
        const isExcluded = excludeDateObjects.some(excludeDate =>
            excludeDate.getTime() === currentDate.getTime()
        );

        // 判断当前日期是否为工作日
        const isWeekday =
            (dayOfWeek >= 1 && dayOfWeek <= 5) ||  // 周一至周五
            (dayOfWeek === 6 && saturday) ||       // 周六（如果配置为工作日）
            (dayOfWeek === 0 && sunday);          // 周日（如果配置为工作日）

        // 如果是工作日且不在排除列表中
        if (isWeekday && !isExcluded) {
            workingDayCount++;
        }
    }

    return workingDayCount;
}

/**
 * 获取本年1月1日到今天的工作日数量，支持自定义周六和周日是否为工作日
 * @param {Array<string|Date>} excludeDates - 要排除的日期列表，可以是日期字符串或Date对象
 * @param {Object} [workdayConfig] - 可选参数，工作日配置对象
 * @param {boolean} [workdayConfig.saturday=false] - 周六是否视为工作日，默认值为false
 * @param {boolean} [workdayConfig.sunday=false] - 周日是否视为工作日，默认值为false
 * @returns {number} 本年到今天的工作日数量
 */
homeMethods.getWorkingYearDaysUntilToday = (excludeDates = [], workdayConfig = {}) => {
    const { saturday = false, sunday = false } = workdayConfig;
    const today = new Date();
    today.setHours(0, 0, 0, 0); // 确保时间部分不影响日期比较

    const year = today.getFullYear();
    let workingDayCount = 0;

    // 将排除日期转换为 Date 对象数组并预处理
    const excludeDateObjects = excludeDates
        .map(date => new Date(date))
        .map(date => {
            date.setHours(0, 0, 0, 0);
            return date;
        });

    // 创建本年1月1日的日期对象
    const startDate = new Date(year, 0, 1); // 1月1日

    // 遍历从1月1日到今天的每一天
    for (let currentDate = new Date(startDate); currentDate <= today; currentDate.setDate(currentDate.getDate() + 1)) {
        const dayOfWeek = currentDate.getDay(); // 0（周日）到 6（周六）

        // 判断当前日期是否为排除日期
        const isExcluded = excludeDateObjects.some(excludeDate =>
            excludeDate.getTime() === currentDate.getTime()
        );

        // 判断当前日期是否为工作日
        const isWeekday =
            (dayOfWeek >= 1 && dayOfWeek <= 5) ||  // 周一至周五
            (dayOfWeek === 6 && saturday) ||       // 周六（如果配置为工作日）
            (dayOfWeek === 0 && sunday);          // 周日（如果配置为工作日）

        // 如果是工作日且不在排除列表中
        if (isWeekday && !isExcluded) {
            workingDayCount++;
        }
    }

    return workingDayCount;
}

/**
 * 判断今天是否是工作日（上班日）
 * @param {Array<string|Date>} excludeDates - 要排除的日期列表，可以是日期字符串或Date对象
 * @param {Object} [workdayConfig] - 可选参数，工作日配置对象
 * @param {boolean} [workdayConfig.saturday=false] - 周六是否视为工作日，默认值为false
 * @param {boolean} [workdayConfig.sunday=false] - 周日是否视为工作日，默认值为false
 * @returns {boolean} true表示今天上班，false表示今天不上班
 */
homeMethods.isWorkingDayToday = (excludeDates = [], workdayConfig = {
    saturday: false,
    sunday: false
}) => {
    const { saturday = false, sunday = false } = workdayConfig;
    const today = new Date();
    today.setHours(0, 0, 0, 0); // 规范化时间，只保留日期部分

    // 判断当前日期是否为排除日期
    const isExcluded = excludeDates.some(date => {
        const excludeDate = new Date(date);
        excludeDate.setHours(0, 0, 0, 0);
        return excludeDate.getTime() === today.getTime();
    });

    if (isExcluded) {
        return false; // 如果今天是排除日期，则不上班
    }

    const dayOfWeek = today.getDay(); // 0（周日）到 6（周六）

    // 判断今天是否是工作日
    return (
        (dayOfWeek >= 1 && dayOfWeek <= 5) ||  // 周一至周五
        (dayOfWeek === 6 && saturday) ||       // 周六（如果配置为工作日）
        (dayOfWeek === 0 && sunday)           // 周日（如果配置为工作日）
    );
}

// 返回时间
homeMethods.convertSeconds = (seconds) => {
    const hours = Math.floor(seconds / 3600);
    const remainingSecondsAfterHours = seconds % 3600;
    const minutes = Math.floor(remainingSecondsAfterHours / 60);
    const secs = remainingSecondsAfterHours % 60;

    return {
        hours: hours < 10? '0' + hours: hours,
        minutes: minutes < 10? '0' + minutes: minutes,
        seconds: secs < 10? '0' + secs: secs
    };
}

// 判断是否工作中
homeMethods.getWorkStatus = (workingHours) => {
    const now = new Date();
    const currentHour = now.getHours();
    const currentMinute = now.getMinutes();
    const currentTimeInMinutes = currentHour * 60 + currentMinute;

    // 检查是否在工作时间段内
    for (const period of workingHours) {
        const [startHour, startMinute] = period.startTime.split(':').map(Number);
        const [endHour, endMinute] = period.endTime.split(':').map(Number);

        const startTimeInMinutes = startHour * 60 + startMinute;
        const endTimeInMinutes = endHour * 60 + endMinute;

        if (currentTimeInMinutes >= startTimeInMinutes && currentTimeInMinutes < endTimeInMinutes) {
            return 0; // 工作中
        }
    }

    // 检查是否还没开始上班
    if (workingHours.length > 0) {
        const [firstStartHour, firstStartMinute] = workingHours[0].startTime.split(':').map(Number);
        const firstStartTimeInMinutes = firstStartHour * 60 + firstStartMinute;

        if (currentTimeInMinutes < firstStartTimeInMinutes) {
            return 1; // 准备上班
        }
    }

    // 检查是否已经下班
    if (workingHours.length > 0) {
        const lastPeriod = workingHours[workingHours.length - 1];
        const [lastEndHour, lastEndMinute] = lastPeriod.endTime.split(':').map(Number);
        const lastEndTimeInMinutes = lastEndHour * 60 + lastEndMinute;

        if (currentTimeInMinutes >= lastEndTimeInMinutes) {
            return 2; // 下班咯
        }
    }

    // 如果以上都不满足，说明在工作时间段之间的休息时间
    return 3; // 休息中
}

/**
 * 将秒数转换为中文时间格式
 * @param {number} seconds - 需要转换的总秒数（可正可负）
 * @returns {string} 中文格式的时间描述，如 "X小时Y分钟Z秒"
 */
homeMethods.formatSecondsToChinese = (seconds) => {
    // 计算各时间单位
    const hours = Math.floor(seconds / 3600);
    seconds %= 3600;
    const minutes = Math.floor(seconds / 60);
    seconds %= 60;
    const secs = Math.floor(seconds);

    // 构建中文描述
    let result = '';
    if (hours > 0) result += `${hours}时`;
    if (minutes > 0) result += `${minutes}分`;
    if (secs > 0 || result === '') result += `${secs}秒`;

    return result;
}

export default homeMethods
